<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\CreateGoodsRequest;
use App\Http\Requests\UpdateGoodsRequest;
use App\Models\Cart;
use App\Models\Category;
use App\Models\Goods;
use App\Models\GoodsAttribute;
use App\Models\GoodsContent;
use App\Models\GoodsSlideshow;
use App\Repositories\GoodsRepository;
use App\Http\Controllers\AppBaseController;
use App\Repositories\PicturesRepository;
use Illuminate\Http\Request;
use Flash;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

class GoodsController extends AppBaseController
{
    /** @var  GoodsRepository */
    private $goodsRepository;
    private $pic;

    public function __construct(GoodsRepository $goodsRepo, PicturesRepository $picturesRepository)
    {
        $this->goodsRepository = $goodsRepo;
        $this->pic = $picturesRepository;
    }

    /**
     * Display a listing of the Goods.
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $model = new Goods();
        $model = $model->where('status',1);
        $seesion_search = $request->seesion_search;
        $session = session();
        if($request->seesion_clear){
            $session->forget('search_category_id');
            $session->forget('search_name');
            $session->forget('search_page');
        }
        $category_id = request('category_id',$seesion_search?session('search_category_id'):null);
        if($category_id){
            session(['search_category_id'=>$category_id]);
            $model = Category::find($category_id)->goods()->where('status',1);
        }else{
            $session->forget('search_category_id');
        }

        $name = request('name',$seesion_search?session('search_name'):null);
        if($name){
            session(['search_name'=>$name]);
            $model = $model->where('name','like',"%$name%");
        }else{
            $session->forget('search_name');
        }

        $order = request('order','sort');
        $sort = request('sort','desc');
        $model = $model->orderBy($order,$sort);
        if(session('search_page') && $seesion_search)
            $request->merge(['page'=>session('search_page')]);
        else
            $session->forget('search_page');
        if($request->page){
            session(['search_page'=>$request->page]);
        }
        $goods = $model->paginate(20);
        return view('goods.index')
            ->with('goods', $goods)->with('categories',Category::all())->with('request',array_merge($request->all(),[
                'name'=>$name,
                'order'=>$order,
                'sort'=>$sort,
                'category_id'=>$category_id,
            ]));
    }

    /**
     * Show the form for creating a new Goods.
     *
     * @return Response
     */
    public function create()
    {
        $cats = Category::all();
        return view('goods.create')
            ->with('cats', $cats);
    }

    /**
     * Store a newly created Goods in storage.
     *
     * @param CreateGoodsRequest $request
     *
     * @return Response
     */
    public function store(CreateGoodsRequest $request)
    {
        $input = $request->all();

        $goods = $this->goodsRepository->create($input);

        //详情图
        $_content_images = $request->file('content_images');
        $content_images = [];
        if(!empty($_content_images)){
            foreach ($_content_images as $content_image) {
                $_res = $this->pic->uploadByHash($content_image,"goods_content",null,null);
                $_content = new GoodsContent([
                    'url'=>$_res->url
                ]);
                if($_res){
                    $content_images[] = $_res;
                    $goods->contents()->save($_content);
                }

            }
        }
        //轮播图
        $_slideshow_images = $request->file('slideshow_images');
        $slideshow_images = [];
        if(!empty($_slideshow_images)){
            GoodsSlideshow::where('goods_id',$goods->id)->update(['goods_id'=>0]);
            foreach ($_slideshow_images as $slideshow_image) {
                $_res = $this->pic->uploadByHash($slideshow_image,"goods_slideshow",null,null);
                $_goodsSlideshow = new GoodsSlideshow([
                    'url'=>$_res->url
                ]);
                if($_res){
                    $slideshow_images[] = $_res;
                    $goods->slideshow()->save($_goodsSlideshow);
                }

            }
        }

        //背景图
        if($request->hasFile('image')){
            $image = $this->pic->uploadByHash($request->file('image'),"goods_image",null,null);
            $goods->image = $image->url;
        }


        //属性
        $attribute = [];
        $hasAttribute = $request->attribute_name;
        $attribute_market_price = $request->attribute_market_price;
        $attribute_sale_price = $request->attribute_sale_price;
        $attribute_sales_count = $request->attribute_sales_count;
        $attribute_day_buy_number = $request->attribute_day_buy_number;
        $attribute_number = $request->attribute_number;
        if(isset($hasAttribute) && !empty($hasAttribute)){
            $goods->number = 0;
            foreach ($hasAttribute as $k=>$v) {
                $_attribute = new GoodsAttribute([
                    'name'=>$v?$v:'默认',
                    'market_price'=>$attribute_market_price[$k],
                    'sale_price'=>$attribute_sale_price[$k],
                    'sales_count'=>$attribute_sales_count[$k],
                    'day_buy_number'=>$attribute_day_buy_number[$k],
                    'number'=>$attribute_number[$k],
                ]);
                $attribute[] = $_attribute;
                $goods->attributes()->save($_attribute);
                $goods->number +=  $attribute_number[$k];
            }
        }
        $goods->save();
        //分类
        $goods->categories()->sync($request->cat_id);
        Flash::success('Goods saved successfully.');

        return redirect(route('goods.index',['seesion_search'=>1]));
    }

    /**
     * Display the specified Goods.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $goods = $this->goodsRepository->findWithoutFail($id);

        if (empty($goods)) {
            Flash::error('Goods not found');

            return redirect(route('goods.index'));
        }

        return view('goods.show')->with('goods', $goods);
    }

    /**
     * Show the form for editing the specified Goods.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $goods = $this->goodsRepository->findWithoutFail($id);
        if (empty($goods)) {
            Flash::error('Goods not found');

            return redirect(route('goods.index'));
        }
        $has_cat_ids = [];
        foreach ($goods->categories as $has_cat) {
            $has_cat_ids[] = $has_cat->id;
        }
        $cats = Category::all();

        return view('goods.edit')->with('goods', $goods)->with('cats', $cats)->with('has_cat_ids', $has_cat_ids);
    }

    /**
     * Update the specified Goods in storage.
     *
     * @param  int              $id
     * @param UpdateGoodsRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateGoodsRequest $request)
    {
        $goods = $this->goodsRepository->findWithoutFail($id);

        if (empty($goods)) {
            Flash::error('Goods not found');

            return redirect(route('goods.index'));
        }
        $goods = $this->goodsRepository->update($request->all(), $id);
        $day_buy_number = request('day_buy_number',0);
        if($day_buy_number>0){\
            Cart::where([
                ['number','>',$day_buy_number],
                ['goods_id','=',$id],
                ['attribute_id','=',0],
            ])->update(['number'=>$day_buy_number]);
        }
        //详情图
        $_content_images = $request->content_images;
        $content_images = [];
        if(!empty($_content_images)){
            GoodsContent::where('goods_id',$goods->id)->delete();
            foreach ($_content_images as $content_image) {
                if(!is_string($content_image)){
                    $_res = $this->pic->uploadByHash($content_image,"goods_content",null,null);
                   $_url = $_res->url;
                }else{
                    $_url = $content_image;
                }
                $_content = new GoodsContent([
                    'url'=>$_url
                ]);
                $content_images[] = $_url;
                $goods->contents()->save($_content);
            }
        }
        //轮播图
        $_slideshow_images = $request->slideshow_images;
        $slideshow_images = [];
        if(!empty($_slideshow_images)){
            GoodsSlideshow::where('goods_id',$goods->id)->update(['goods_id'=>0]);
            foreach ($_slideshow_images as $slideshow_image) {
                if(!is_string($slideshow_image)){
                    $_res = $this->pic->uploadByHash($slideshow_image,"goods_slideshow",null,null);
                    $_url = $_res->url;
                }else{
                    $_url = $slideshow_image;
                }
                $_goodsSlideshow = new GoodsSlideshow([
                    'url'=>$_url
                ]);
                $slideshow_images[] = $_url;
                $goods->slideshow()->save($_goodsSlideshow);
            }
        }

        //背景图
        if($request->hasFile('image')){
            $image = $this->pic->uploadByHash($request->file('image'),"goods_image",null,null);
            $goods->image = $image->url;
        }


        //属性
        $attribute = [];
        $hasAttribute = $request->attribute_name;
        $attribute_market_price = $request->attribute_market_price;
        $attribute_sale_price = $request->attribute_sale_price;
        $attribute_sales_count = $request->attribute_sales_count;
        $attribute_day_buy_number = $request->attribute_day_buy_number;
        $attribute_number = $request->attribute_number;

        GoodsAttribute::where('goods_id',$goods->id)->update(['status'=>2]);

        //已有属性处理
        $has_attribute = $request->has_attribute;
        if($has_attribute && !empty($has_attribute)){
            $goods->number = 0;
            foreach ($has_attribute as $item) {
                $_attribute_name = 'attribute_'.$item.'_name';
                $_attribute_market_price = 'attribute_'.$item.'_market_price';
                $_attribute_sale_price = 'attribute_'.$item.'_sale_price';
                $_attribute_sales_count = 'attribute_'.$item.'_sales_count';
                $_attribute_day_buy_number = 'attribute_'.$item.'_day_buy_number';
                $_attribute_number = 'attribute_'.$item.'_number';
                $_arrtibure = GoodsAttribute::find($item);
                GoodsAttribute::where('id',$_arrtibure->id)->update([
                    'goods_id' => $goods->id,
                    'name' => $request->{$_attribute_name},
                    'market_price' => $request->{$_attribute_market_price},
                    'sale_price' => $request->{$_attribute_sale_price},
                    'sales_count' => $request->{$_attribute_sales_count},
                    'number' => $request->{$_attribute_number},
                    'day_buy_number' => $request->{$_attribute_day_buy_number},
                    'status' => 1,
                ]);
                $goods->number +=  $request->{$_attribute_number};

                if($_attribute_day_buy_number>0){
                    Cart::where([
                        ['number','>',$_attribute_day_buy_number],
                        ['goods_id','=',$id],
                        ['attribute_id','=',$_arrtibure->id],
                    ])->update(['number'=>$_attribute_day_buy_number]);
                }
            }
        }
        //NEW
        if(isset($hasAttribute) && !empty($hasAttribute)){
            if($has_attribute && !empty($has_attribute)) {
            }else{
                $goods->number = 0;
            }
            foreach ($hasAttribute as $k=>$v) {
                $_attribute = new GoodsAttribute([
                    'name'=>$v?$v:'默认',
                    'market_price'=>$attribute_market_price[$k],
                    'sale_price'=>$attribute_sale_price[$k],
                    'sales_count'=>$attribute_sales_count[$k],
                    'day_buy_number'=>$attribute_day_buy_number[$k],
                    'number'=>$attribute_number[$k],
                ]);
                $attribute[] = $_attribute;
                $goods->attributes()->save($_attribute);

                $goods->number +=  $attribute_number[$k];
            }
        }
        $goods->save();

        $goods->categories()->sync($request->cat_id);

        Flash::success('Goods updated successfully.');

        return redirect(route('goods.index', ['seesion_search'=>1]));
    }

    /**
     * Remove the specified Goods from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $goods = $this->goodsRepository->findWithoutFail($id);

        if (empty($goods)) {
            Flash::error('Goods not found');

            return redirect(route('goods.index'));
        }
        $goods->status = 0;
        $goods->save();
//        $this->goodsRepository->delete($id);

        Flash::success('Goods deleted successfully.');

        return redirect(route('goods.index',['seesion_search'=>1]));
    }
    
    public function del($id)
    {
        $goods = $this->goodsRepository->findWithoutFail($id);

        if (empty($goods)) {
            Flash::error('Goods not found');

            return redirect(route('goods.index'));
        }
        $goods->status = 0;
        $goods->save();
//        $this->goodsRepository->delete($id);

        Flash::success('Goods deleted successfully.');

        return redirect(route('goods.index',['seesion_search'=>1]));
    }

    public function batchOperation()
    {
        $ids = request('ids');
        $goods = Goods::whereIn('id',$ids)->get();
        return view('goods.batchOperation')->with('goods', $goods);
    }

    public function panel()
    {
        $category = Category::orderBy('sort')->get();
        $id = request('cid');
        $cate = Category::where('id',$id)->first();
        $goods = $cate->goods()->where('status',1)->get();
        foreach($goods as $v){
            $v->load('attributesByStatus');
        }
        return view('goods.panel')->with('categories', $category)->with('goods_arr',$goods );
    }

    public function batchOperationPost(Request $request)
    {
        $ids = $request->ids;
        $goods = Goods::whereIn('id',$ids)->get();
        foreach ($ids as $id) {
            $_name = $id.'_name';
            $_sn = $id.'_sn';
            $_title = $id.'_title';
            $_click_count = $id.'_click_count';
            $_sales_count = $id.'_sales_count';
            $_number = $id.'_number';
            $_market_price = $id.'_market_price';
            $_sale_price = $id.'_sale_price';
            $_unit = $id.'_unit';
            $_sale_start_date = $id.'_sale_start_date';
            $_sale_end_date = $id.'_sale_end_date';
            $_sort = $id.'_sort';
            $_data = [
                'name'=>$request->{$_name},
                'sn'=>$request->{$_sn},
                'title'=>$request->{$_title},
                'click_count'=>$request->{$_click_count},
                'sales_count'=>$request->{$_sales_count},
                'market_price'=>$request->{$_market_price},
                'sale_price'=>$request->{$_sale_price},
                'unit'=>$request->{$_unit},
                'sale_start_date'=>$request->{$_sale_start_date},
                'sale_end_date'=>$request->{$_sale_end_date},
                'sort'=>$request->{$_sort},
            ];
            if(Goods::find($id)->attributesByStatus->count()==0)
                $_data['number'] = $request->{$_number};
            Goods::where('id',$id)->update($_data);
        }
        Flash::success('修改成功 successfully.');
        return view('goods.batchOperation')->with('goods', $goods);
    }
}
